import { Injectable } from '@angular/core'
import { MatDialog } from '@angular/material/dialog'
import { AdConfirmComponent, ConfirmContent, ConfirmParams } from './confirm.component'

@Injectable()
export class AdConfirmService {
  config: ConfirmParams = {
    content: '',
    type: 'success',
    isShowCancel: true,
    isShowConfirm: true,
    cancelText: '取消',
    confirmText: '确认',
    cancelIsReject: true,
    data: {},
  }
  constructor(private dialog: MatDialog) {}
  async open<T>(content: ConfirmContent, confirmParams: Omit<ConfirmParams<T>, 'content'> = {}) {
    confirmParams = Object.assign({}, this.config, confirmParams, { content })
    const result = await this.dialog
      .open(AdConfirmComponent, {
        panelClass: 'ad-confirm-pane',
        data: confirmParams,
      })
      .afterClosed()
      .toPromise()
    if (result === true) {
      return true
    } else if (confirmParams.cancelIsReject) {
      return Promise.reject('confirm reject')
    } else {
      return false
    }
  }
  success<T>(
    content: ConfirmContent,
    confirmParams: Omit<ConfirmParams<T>, 'type' | 'content'> = {}
  ) {
    return this.open(content, { ...confirmParams, type: 'success' })
  }
  warning<T>(
    content: ConfirmContent,
    confirmParams: Omit<ConfirmParams<T>, 'type' | 'content'> = {}
  ) {
    return this.open(content, { ...confirmParams, type: 'warning' })
  }
  error<T>(
    content: ConfirmContent,
    confirmParams: Omit<ConfirmParams<T>, 'type' | 'content'> = {}
  ) {
    return this.open(content, { ...confirmParams, type: 'error' })
  }
}
